package com.alexander.cloundexplorer.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.alexander.cloundexplorer.R;
import com.alexander.cloundexplorer.adapter.TrashFilesAdapter;
import com.alexander.cloundexplorer.bean.params.ClearTrashParams;
import com.alexander.cloundexplorer.bean.params.User;
import com.alexander.cloundexplorer.bean.params.GetTrashFileParams;
import com.alexander.cloundexplorer.bean.response.BaseResponse;
import com.alexander.cloundexplorer.bean.response.FileTrashResponse;
import com.alexander.cloundexplorer.dialog.TrashFileOptionsDialog;
import com.alexander.cloundexplorer.util.Constants;
import com.alibaba.fastjson.JSON;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * @author Administrator
 * 展示文件列表的页面,没有分类，根据传入的文件夹ID
 * （“root”说明是需要请求文件根目录）来请求数据进行展示
 */
public class TrashActivity extends BaseActivity implements TrashFilesAdapter.OnItemClickLisnter
{
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private User user = new User();
    private List<FileTrashResponse> list = new ArrayList<>();
    private TrashFilesAdapter trashFilesAdapter;
    private TrashFileOptionsDialog trashFileOptionsDialog;
    private GetTrashFileParams getTrashFileParams = new GetTrashFileParams();
    private ClearTrashParams clearTrashParams = new ClearTrashParams();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filelist_layout);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        user = (User) intent.getExtras().getSerializable("user");
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        trashFilesAdapter = new TrashFilesAdapter(this, list);
        trashFilesAdapter.setOnItemClickLisnter(this);
        recyclerView.setAdapter(trashFilesAdapter);

        getTrashFileParams.setAccount(user.getPhone());
        getTrashFileParams.setPassword(user.getPassword());
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        OkHttpUtils
                .post()
                .url(Constants.IP.concat("/fileController/getTrashFile"))
                .addParams("params", JSON.toJSONString(getTrashFileParams))
                .build()
                .execute(new StringCallback()
                {
                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                        showTip(e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id)
                    {
                        showTip(response);
                        BaseResponse baseResponse = JSON.parseObject(response, BaseResponse.class);
                        list.removeAll(list);
                        list.addAll(JSON.parseArray(baseResponse.getData().toString(), FileTrashResponse.class));
                        trashFilesAdapter.notifyDataSetChanged();
                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_options_trash, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            /**清空回收站*/
            case R.id.clear:
                new AlertDialog.Builder(TrashActivity.this)
                    .setMessage("清空回收站？")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton("确认", new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            dialog.dismiss();
                            clearTrashParams.setAccount(user.getPhone());
                            clearTrashParams.setPassword(user.getPassword());
                            clearTrashParams.setIds(getTrashFileIds());
                            OkHttpUtils
                                    .post()
                                    .url(Constants.IP.concat("/fileController/clearTrash"))
                                    .addParams("params", JSON.toJSONString(clearTrashParams))
                                    .build()
                                    .execute(new StringCallback()
                                    {
                                        @Override
                                        public void onError(Call call, Exception e, int id)
                                        {}

                                        @Override
                                        public void onResponse(String response, int id)
                                        {
                                            showTip(response);
                                        }
                                        @Override
                                        public void onAfter(int id)
                                        {
                                            super.onAfter(id);
                                        }
                                    });
                        }
                    })
                    .show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onItemClick(int position)
    {
        showTip("打开文件".concat(list.get(position).getFileTrashName()));
    }

    @Override
    public void onMoreClick(int position)
    {
        showTip("更多");
        trashFileOptionsDialog = new TrashFileOptionsDialog(TrashActivity.this, list.get(position), user);
        trashFileOptionsDialog.show();
    }

    private String getTrashFileIds()
    {
        StringBuffer ids = new StringBuffer();
        if(list != null && list.size() > 0)
        {
            for (int i = 0; i < list.size(); i++)
            {
                ids.append(list.get(i).getFile_id()).append(",");
            }
        }
        ids = ids.deleteCharAt(ids.length() - 1);
        return ids.toString();
    }
}